import 'dart:async';

import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';

import '../models/map_location.model.dart';

class MapService {
  /// Searchs suggestion by keyword.
  static Future<List<String>> searchSuggestion(
      String keyword, String? city) async {
    final completer = Completer<List<String>>();

    final option = BMFSuggestionSearchOption(
      keyword: keyword,
      cityname: city,
    );

    final search = BMFSuggestionSearch();

    search.onGetSuggestSearchResult(callback: (result, errorCode) {
      completer
          .complete(result.suggestionList?.map((p) => p.key!).toList() ?? []);
    });

    search.suggestionSearch(option);

    return completer.future;
  }

  /// Searchs poi by keyword.
  static Future<List<MapLocation>> searchPoi(
      String keyword, String? city) async {
    final completer = Completer<List<MapLocation>>();

    final option = BMFPoiCitySearchOption(
      keyword: keyword,
      city: city,
    );

    final search = BMFPoiCitySearch();

    search.onGetPoiCitySearchResult(callback: (result, errorCode) {
      completer.complete(result.poiInfoList
              ?.where((p) => p.pt != null)
              .map((p) => MapLocation.fromPoi(p))
              .toList() ??
          []);
    });

    search.poiCitySearch(option);

    return completer.future;
  }

  /// Searchs poi info by coordinates.
  static Future<MapLocation> searchReverseGeoCode(
      BMFCoordinate coordinate) async {
    final completer = Completer<MapLocation>();

    final option = BMFReverseGeoCodeSearchOption(
      location: coordinate,
      isLatestAdmin: true,
    );

    final search = BMFReverseGeoCodeSearch();

    search.onGetReverseGeoCodeSearchResult(callback: (result, errorCode) {
      completer.complete(MapLocation.fromReverseGeoCodeSearchResult(result));
    });

    search.reverseGeoCodeSearch(option);

    return completer.future;
  }
}
